package com.draw.cli.gui.panel;

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

import com.draw.core.User;

public class UserTable extends JPanel {
	private static final long serialVersionUID = -5304935093239390262L;

	private JTable table;
	private JScrollPane scroll;

	private UserTableModele modele;

	public UserTable() {
		this.setLayout(new BorderLayout());
		this.modele = new UserTableModele();
		this.table = new JTable(this.modele);
		this.scroll = new JScrollPane(this.table);
		this.add(this.scroll);
	}

	public void setUsers(List<User> users) {
		this.modele.setUsers(users);
	}

	public JTable getTable() {
		return this.table;
	}

	public User getSelectedUser() {
		int row = this.table.getSelectedRow();
		return this.modele.getValueAtRow(row);
	}

	class UserTableModele extends AbstractTableModel {
		private static final long serialVersionUID = 1876332473544914731L;

		private final String[] header = { "Utilisateur", "Points" };
		private ArrayList<User> users;

		public UserTableModele() {
			this.users = new ArrayList<User>();
		}

		public void setUsers(List<User> users) {
			this.users.clear();
			if (users != null) {
				for (User u : users) {
					this.addUser(u);
				}
			}
			this.fireTableDataChanged();
		}

		public void addUser(User user) {
			this.users.add(user);
		}

		public List<User> getUsers() {
			return this.users;
		}

		@Override
		public int getColumnCount() {
			return this.header.length;
		}

		@Override
		public int getRowCount() {
			return this.users.size();
		}

		public String getColumnName(int columnIndex) {
			return this.header[columnIndex];
		}

		@Override
		public Object getValueAt(int arg0, int arg1) {
			if (arg0 < this.users.size() && arg0 >= 0) {
				User user = this.users.get(arg0);
				if (arg1 == 1) {
					Integer p = user.getPoints();
					if (p==null){
						return new Integer(0);
					} else {
						return p;
					}
				} else {
					return user.getUsername();
				}
			} else {
				return null;
			}
		}

		public User getValueAtRow(int row) {
			if (row >= this.users.size() || row < 0) {
				return null;
			} else {
				return this.users.get(row);
			}
		}

		public boolean isCellEditable(int row, int col) {
			return false;
		}
	}
}
